﻿using MediatR;
using Sgr.Application.Commands;
using Sgr.Security.VerifyCode;

namespace Sgr.Indentity.Application.Commands
{
    /// <summary>
    /// 处理验证码验证命令的处理器
    /// </summary>
    public class VerifyCodeCheckCommandHandle : IRequestHandler<VerifyCodeCheckCommand, CommandResult<bool>>
    {
        private readonly IVerifyCodeService _verifyCodeService;
        private readonly ILogger<VerifyCodeCheckCommandHandle> _logger;

        public VerifyCodeCheckCommandHandle(IVerifyCodeService verifyCodeService, ILogger<VerifyCodeCheckCommandHandle> logger)
        {
            _verifyCodeService = verifyCodeService ?? throw new ArgumentNullException(nameof(verifyCodeService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 处理验证码验证命令
        /// </summary>
        /// <param name="request">验证码验证命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>包含验证结果的命令执行结果</returns>
        public async Task<CommandResult<bool>> Handle(VerifyCodeCheckCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证验证码
                bool isValid = await _verifyCodeService.VerifyAsync(
                    request.ReceiverType,       // 验证码接收方式（Phone/Email）
                    request.Receiver,          // 接收地址（手机号/邮箱）
                    request.Purpose,           // 验证码用途
                    request.VerificationCode,  // 验证码
                    request.IsTemporary,       // 是否为临时性验证
                    cancellationToken);        // 取消令牌

                // 返回验证结果
                return CommandResult.Success(isValid);
            }
            catch (Exception ex)
            {
                // 捕获异常并记录日志（假设有日志记录器）
                _logger.LogError(ex, "验证码验证失败: {Receiver}, {Purpose}", request.Receiver, request.Purpose);

                // 返回错误结果
                return CommandResult.Error<bool>("验证码验证失败");
            }
        }
    }
}